import 'dart:async';
// import 'dart:math';
import 'package:bitcoin_mine/api/api.dart';
import 'package:bitcoin_mine/model/check_in.dart';
import 'package:bitcoin_mine/model/contract.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../common/global.dart';
import '../http/http_request.dart';

class ContractController extends GetxController {
  // 签到相关
  final Rx<CheckIn?> checkIn = Rx<CheckIn?>(null);

  // 排序弹窗
  final RxBool isSortingMenuVisible = false.obs;
  final RxString selectedSortType = 'VIP_CONTRACT'.obs;

  // 领取免费合约
  final RxBool receivingFree = false.obs;

  // 合约比特币数量实时更新（展示用双精度）
  // final RxMap<int, Bi> contractBitcoinAmounts = <int, double>{}.obs;
  // 使用高精度整数存储，单位为 1e-15 BTC，避免双精度丢失
  final RxMap<int, BigInt> contractAmountUnits = <int, BigInt>{}.obs;
  static const int _scale = 15;
  static const double _scalePow = 1e15;
  final RxMap<int, int> contractRemainingHours = <int, int>{}.obs;
  final RxMap<int, int> contractRemainingMinutes = <int, int>{}.obs;

  Timer? _contractUpdateTimer;

  // 动画控制器
  final RxBool showAnimation = false.obs;
  late AnimationController animationController;

  @override
  void onInit() {
    super.onInit();
    initializeCheckIn();
    initializeContracts();
    _startContractUpdateTimer();
  }

  // 将 double 转为 1e-16 单位 BigInt（字符串安全转换，避免溢出）
  BigInt _toUnits(double value) {
    final String s = value.toStringAsFixed(_scale);
    final bool neg = s.startsWith('-');
    final String digits = s.replaceAll('-', '').replaceAll('.', '');
    BigInt units = BigInt.parse(digits);
    return neg ? -units : units;
  }

  double _unitsToDouble(BigInt units) {
    return units.toDouble() / _scalePow;
  }

  @override
  void onClose() {
    _contractUpdateTimer?.cancel();
    super.onClose();
  }

  void initializeCheckIn() {
    // HttpRequest.instance.requestNetwork<CheckIn>(
    //   Api.signInfo,
    //   method: "GET",
    //   onSuccess: (data) {
    //     checkIn.value = data;
    //   },
    //   onError: (error, stackTrace) {
    //     print('获取签到信息失败: $error');
    //   },
    // );

    HttpRequest.instance.requestCommon("GET", Api.signInfo).then((value) {
      // print('获取签到信息11: $value');

      // HttpRequest.instance.requestCommon("GET", Api.signInfo).then((value) {
      //   print('获取签到信息22: $value');
      // });
      HttpRequest.instance.requestNetwork<CheckIn>(
        Api.signInfo,
        method: "GET",
        onSuccess: (data) {
          checkIn.value = data;
        },
        onError: (error, stackTrace) {
          print('获取签到信息失败: $error');
        },
      );
    });
  }

  void initializeContracts() {
    Global.updateContract().then((_) {
      updateContractAmounts();
    });
  }

  // 初始化合约比特币数量
  void updateContractAmounts() {
    print('updateContractAmounts');
    // contractBitcoinAmounts.clear();
    contractAmountUnits.clear();
    contractRemainingHours.clear();
    contractRemainingMinutes.clear();
    for (final contract in Global.contracts) {
      if (isContractExpired(contract)) {
        final BigInt currentUnits = BigInt.zero;
        final BigInt incrementUnits = BigInt.from(
          (contract.hashrate * 100 * getContractElapsedSeconds(contract))
              .round(),
        );
        final BigInt newUnits = currentUnits + incrementUnits;
        contractAmountUnits[contract.id] = newUnits;
        continue;
      }
      if (contract.coin == null) {
        // contract.coin = contract;
      }
      // 初始化为整数单位（1e-15）
      final BigInt initUnits =
          contract.coin != null ? _toUnits(contract.coin!) : BigInt.zero;
      // 初始化为整数单位（1e-16）
      // final BigInt initUnits =
      //     contract.coin != null
      //         ? BigInt.from((1234 * pow(10, 16)).round())
      //         : BigInt.from(1234 * pow(10, 16));
      contractAmountUnits[contract.id] = initUnits;
      // 同步到展示用双精度
      // contractBitcoinAmounts[contract.id] = _unitsToDouble(initUnits);
      // print('init units: ${_contractAmountUnits[contract.id]}');
      contractRemainingHours[contract.id] = getContractRemainingHours(contract);
      contractRemainingMinutes[contract.id] = getContractRemainingMinutes(
        contract,
      );
    }
  }

  // 启动合约更新定时器
  void _startContractUpdateTimer() {
    _contractUpdateTimer?.cancel();
    _contractUpdateTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      _updateContractBitcoinAmounts();
    });
  }

  // 更新合约比特币数量
  void _updateContractBitcoinAmounts() {
    final beijingNow = Global.getBeijingTime();
    // bool hasExpiredContracts = false; // 预留：需要时可用于触发刷新

    for (final contract in Global.contracts) {
      if (contract.status != 1) {
        continue;
      }
      final endTime = DateTime.parse(contract.contract_end_at);
      contractRemainingHours[contract.id] = getContractRemainingHours(contract);
      contractRemainingMinutes[contract.id] = getContractRemainingMinutes(
        contract,
      );
      if (beijingNow.isBefore(endTime) && contract.status == 1) {
        // 使用整数单位累加：1e-16 单位下，每秒增量 = hashrate * 1e-14 BTC => 单位增量 = hashrate * 100
        final BigInt currentUnits =
            contractAmountUnits[contract.id] ?? BigInt.zero;
        final BigInt incrementUnits = BigInt.from(
          (contract.hashrate * 100).round(),
        );
        final BigInt newUnits = currentUnits + incrementUnits;
        contractAmountUnits[contract.id] = newUnits;
        // 同步展示用双精度
        // contractBitcoinAmounts[contract.id] = _unitsToDouble(newUnits);
      } else if (beijingNow.isAfter(endTime) && contract.status == 1) {
        // 合约已过期（如需自动刷新，可恢复 hasExpiredContracts 逻辑）
      }
    }
    contractAmountUnits.refresh();
    // contractBitcoinAmounts.refresh();

    // 如果有过期合约，刷新合约列表
    // if (hasExpiredContracts) {
    //   _refreshExpiredContracts();
    // }
  }

  // 刷新过期合约
  // void _refreshExpiredContracts() {
  //   Global.updateContract().then((_) {
  //     updateContractAmounts();
  //     print('已刷新过期合约列表');
  //   });
  // }

  // 获取合约当前比特币数量
  BigInt getContractBitcoinAmount(int contractId) {
    return contractAmountUnits[contractId] ?? BigInt.zero;
  }

  // 领取免费合约
  void receiveFreeContract() {
    if (receivingFree.value) return;
    receivingFree.value = true;
    HttpRequest.instance.requestNetwork<List<Contract>>(
      Api.receiveFreeContract,
      method: "GET",
      onSuccess: (data) {
        if (data != null) {
          // Global.contracts.value = data;
          print('领取免费合约成功: ${Global.contracts.length}');
          Global.updateMineInfo();
        }
        receivingFree.value = false;
      },
      onError: (error, stackTrace) {
        receivingFree.value = false;
      },
    );
  }

  // 执行签到
  void performCheckIn() {
    if (checkIn.value == null) return;

    // 找到当前可签到的日期
    final currentDate = checkIn.value!.current_date;
    final todayDetail =
        checkIn.value!.details
                .where(
                  (detail) =>
                      detail.checkin_date == currentDate &&
                      detail.is_checkin == 0,
                )
                .isNotEmpty
            ? checkIn.value!.details.firstWhere(
              (detail) =>
                  detail.checkin_date == currentDate && detail.is_checkin == 0,
            )
            : null;

    if (todayDetail != null) {
      // 调用签到API
      HttpRequest.instance.requestNetwork<CheckInDetail>(
        Api.signIn, // 使用现有的API
        method: "POST",
        params: {'date': currentDate, 'makeup': todayDetail.is_makeup},
        onSuccess: (data) {
          // 签到成功后重新获取数据
          initializeCheckIn();
          initializeContracts();
          showAnimation.value = true;
          animationController.forward();
        },
        onError: (error, stackTrace) {
          Get.snackbar(
            '错误',
            '签到失败: $error',
            snackPosition: SnackPosition.BOTTOM,
          );
        },
      );
    } else {
      Get.snackbar('提示', '今日已签到或暂无可签到日期', snackPosition: SnackPosition.BOTTOM);
    }
  }

  // VIP合约列表 - 使用真实数据
  List<Contract> get allContracts {
    return Global.contracts;
  }

  // 获取合约状态文本
  String getContractStatusText(Contract contract) {
    final status = contract.status;
    switch (status) {
      case 0:
        return 'INACTIVE';
      case 1:
        return 'ACTIVE';
      case 2:
        return 'EXPIRED';
      default:
        return 'UNKNOWN';
    }
  }

  // 获取合约类型文本
  String getContractTypeText(Contract contract) {
    switch (contract.type) {
      // 1免费合约，2广告合约，3签到合约，4VIP合约，5邀请合约
      case 1:
        return 'FREE Contract';
      case 2:
        return 'AD Contract';
      case 3:
        return 'CHECKIN Contract';
      case 4:
        return 'VIP Contract';
      case 5:
        return 'INVITE Contract';
      default:
        return 'UNKNOWN';
    }
  }

  // 获取合约剩余时间（小时）
  int getContractRemainingHours(Contract contract) {
    final endTime = DateTime.parse(contract.contract_end_at);
    final beijingNow = Global.getBeijingTime();
    final difference = endTime.difference(beijingNow);
    return difference.inHours.clamp(0, contract.hours);
  }

  // 获取合约剩余时间（分钟）
  int getContractRemainingMinutes(Contract contract) {
    final endTime = DateTime.parse(contract.contract_end_at);
    final beijingNow = Global.getBeijingTime();
    final difference = endTime.difference(beijingNow);
    return difference.inMinutes % 60;
  }

  // 检查合约是否过期
  bool isContractExpired(Contract contract) {
    final endTime = DateTime.parse(contract.contract_end_at);
    final beijingNow = Global.getBeijingTime();
    return beijingNow.isAfter(endTime);
  }

  // 获取合约已进行的秒数；若已过期则返回合约总持续秒数
  int getContractElapsedSeconds(Contract contract) {
    final DateTime startTime = DateTime.parse(contract.contract_start_at);
    final DateTime endTime = DateTime.parse(contract.contract_end_at);
    final DateTime beijingNow = Global.getBeijingTime();

    if (beijingNow.isBefore(startTime)) {
      return 0;
    }

    if (beijingNow.isAfter(endTime)) {
      return endTime.difference(startTime).inSeconds;
    }

    return beijingNow.difference(startTime).inSeconds;
  }

  // 每日签到奖励数据 - 移除虚构数据，使用真实API数据
  List<CheckInDetail> get dailyRewards {
    return checkIn.value?.details ?? [];
  }

  // 获取当前可签到的天数
  int getCurrentSignInDay() {
    if (checkIn.value == null) return 1;

    final currentDate = checkIn.value!.current_date;
    for (int i = 0; i < checkIn.value!.details.length; i++) {
      final detail = checkIn.value!.details[i];
      if (detail.checkin_date == currentDate && detail.is_checkin == 0) {
        return i + 1;
      }
    }
    return 7; // 全部签到完成
  }

  // 获取签到状态
  bool isSignInCompleted(int day) {
    if (checkIn.value == null || day > checkIn.value!.details.length) {
      return false;
    }
    return checkIn.value!.details[day - 1].is_checkin == 1;
  }

  // 获取当前签到日
  CheckInDetail? getCurrentSignInDetail() {
    if (checkIn.value == null) return null;

    final currentDate = checkIn.value!.current_date;
    try {
      return checkIn.value!.details.firstWhere(
        (detail) =>
            detail.checkin_date == currentDate && detail.is_checkin == 0,
      );
    } catch (e) {
      return null;
    }
  }

  // 显示/隐藏排序菜单
  void toggleSortingMenu() {
    isSortingMenuVisible.value = !isSortingMenuVisible.value;
  }

  // 选择排序类型
  void selectSortType(String type) {
    selectedSortType.value = type;
    isSortingMenuVisible.value = false;
    // TODO: 实现排序逻辑
  }
}
